package com.heima.wemedia.listener;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.heima.common.contants.MessageConstants;
import com.heima.model.wemedia.pojo.WmNews;
import com.heima.wemedia.mapper.WmNewsMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@Slf4j
public class NewsScanResultMessageListener {

    @Resource
    private WmNewsMapper wmNewsMapper;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MessageConstants.NEWS_SCAN_RESULT_QUEUE, durable = "true"),
            exchange = @Exchange(value = MessageConstants.GREEN_SCAN_RESULT_EXCHANGE, type = ExchangeTypes.DIRECT),
            key = MessageConstants.NEWS_SCAN_KEY
    ))
    public void handleNewsScanResult(String message) {
        log.info("接收到文章审核结果消息: {}", message);

        if (StrUtil.isEmpty(message)) {
            return;
        }

        try {
            JSONObject jsonObject = JSONUtil.parseObj(message);
            Long newsId = jsonObject.getLong("newsId");
            String suggestion = jsonObject.getStr("suggestion");
            String reason = jsonObject.getStr("reason");

            // 根据审核结果更新文章状态
            if (newsId != null) {
                WmNews wmNews = new WmNews();
                wmNews.setId(newsId);

                // 根据suggestion判断审核结果
                if ("pass".equals(suggestion)) {
                    // 审核通过，设置状态为4（人工审核通过）
                    wmNews.setStatus(4);
                    wmNews.setReason("审核通过");
                } else {
                    // 审核不通过，设置状态为2（审核失败）
                    wmNews.setStatus(2);
                    wmNews.setReason(reason != null ? reason : "审核不通过");
                }

                wmNewsMapper.updateById(wmNews);
                log.info("更新文章 {} 状态成功，新状态: {}, 原因: {}", newsId, wmNews.getStatus(), wmNews.getReason());
            }
        } catch (Exception e) {
            log.error("处理文章审核结果失败，消息: {}", message, e);
        }
    }
}